package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.EventScheduleDao;
import com.seadragon.app.ksr.model.Event;
import com.seadragon.app.ksr.model.EventSchedule;

@Repository("eventScheduleDao")
public class EventScheduleDaoJpaImpl extends AbstractJpaDao implements EventScheduleDao {

	@Override
	public void save(EventSchedule eventSchedule) {
		entityManager.persist(eventSchedule);
	}
	
	@Override
	public EventSchedule update(EventSchedule eventSchedule) {
		return entityManager.merge(eventSchedule);
	}

	@Override
	public List<EventSchedule> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<EventSchedule> cq = cb.createQuery(EventSchedule.class);
		Root<EventSchedule> root = cq.from(EventSchedule.class);
		cq.select(root);
		TypedQuery<EventSchedule> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public List<EventSchedule> findAllBy(Event event) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<EventSchedule> cq = cb.createQuery(EventSchedule.class);
		Root<EventSchedule> root = cq.from(EventSchedule.class);
		cq.select(root);
		cq.where(cb.equal(root.get("event"), event));
		return entityManager.createQuery(cq).getResultList();
	}

	@Override
	public EventSchedule findById(long id) {
		return entityManager.find(EventSchedule.class, id);
	}

}
